var base = null;
window.app = {};
var cache = {};
var server_host = 'http://www.allin4u.com/ry-web-admin/api/';
var root_host = 'http://www.allin4u.com/';
//var server_host = 'http://192.168.1.103:8080/ry-web-admin/api/';
var storege = window.localStorage;
var HISTORY = "app_history";
var TRANS_PARAM = "tans_param";
base = base || {
	/**
	 * URL管理
	 */
	url: {
		sendVerificationCode : server_host + 'customer/sendVerificationCode',//发送验证码
		addCompanyInfo : server_host + 'company/addCompanyInfo',//新增/修改公司信息
		getCompanyList : server_host + 'company/getCompanyList',//获取公司信息
		delCompanyInfo : server_host + 'company/delCompanyInfo',//删除公司信息
		addVisaApplyCustomerInfo : server_host + 'applyCustomer/addVisaApplyCustomerInfo',//新增申请客户
		updateVisaApplyCustomerInfo : server_host + 'applyCustomer/updateVisaApplyCustomerInfo',//修改申请人信息(基本信息/护照信息/联系方式)
		getVisaApplyCustomerList : server_host + 'applyCustomer/getVisaApplyCustomerList',//获取申请客户
		delVisaApplyCustomerInfo : server_host + 'applyCustomer/delVisaApplyCustomerInfo',//删除申请客户
		customerLogin : server_host + 'customer/customerLogin',//用户登录
		customerRegistered : server_host + 'customer/customerRegistered',//用户注册
		customerVerificationCode : server_host + 'customer/customerVerificationCode',//验证验证码
		forgotPassword : server_host + 'customer/forgotPassword',//忘记密码/设置密码
		updateCuetomerInfo : server_host + 'customer/updateCuetomerInfo',//修改客户信息
		bindingPhone : server_host + 'customer/bindingPhone',//绑定手机
		miniCustomerLogin : server_host + 'customer/miniCustomerLogin',//小程序客户登录
		addEducationInfo : server_host + 'education/addEducationInfo',//新增/修改教育信息
		getEducationList : server_host + 'education/getEducationList',//获取教育信息
		delEducationInfo : server_host + 'education/delEducationInfo',//删除教育信息
		addFamilyInfo : server_host + 'family/addFamilyInfo',//添加/修改家庭信息
		getFamilyList : server_host + 'family/getFamilyList',//获取家庭信息
		delFamilyChildrenInfo : server_host + 'family/delFamilyChildrenInfo',//删除子女信息
		addVisaOutboundRecordsInfo : server_host + 'outboundRecords/addVisaOutboundRecordsInfo',//新增/修改入境信息
		getVisaOutboundRecordsList : server_host + 'outboundRecords/getVisaOutboundRecordsList',//获取入境信息		
		delVisaOutboundRecordsInfo : server_host + 'outboundRecords/delVisaOutboundRecordsInfo',//删除入境信息
		addIDCardFront : server_host + 'visaIdentityCard/addIDCardFront',//添加身份证正面
		addIDCardBack : server_host + 'visaIdentityCard/addIDCardBack',//添加身份正反面
		getIDCardInfo : server_host + 'visaIdentityCard/getIDCardInfo',//获取身份证信息
		delIDCardInfo : server_host + 'visaIdentityCard/delIDCardInfo',//删除身份证信息
		uploadFile : server_host + 'upload/uploadFile',//附件上传
		getAddressList : server_host + 'address/getAddressList',//获取地址信息
		delAddressInfo : server_host + 'address/delAddressInfo',//删除个人地址信息
		setDefaultAddress : server_host + 'address/setDefaultAddress',//设置默认地址
		getAddressInfo : server_host + 'address/getAddressInfo',//获取地址详情
		verificationPassword : server_host + 'customer/verificationPassword',//验证密码
		addFeedbackInfo : server_host + 'feedback/addFeedbackInfo',//添加意见反馈
		addAddressInfo : server_host + 'address/addAddressInfo',//添加/修改地址信息
		getPassportInfo : server_host + 'applyCustomer/getPassportInfo',//获取护照信息
		getBasicInfo : server_host + 'applyCustomer/getBasicInfo',//获取基本信息
		getContactInfo : server_host + 'applyCustomer/getContactInfo',//获取联系方式
		getIntroduce : server_host + 'introduce/getIntroduce',//获取首页banner
		getVisaHomePageList : server_host + 'visaApi/getVisaHomePageList',//签证首页信息
		getGoodsByGoodsType : server_host + 'goods/getGoodsByGoodsType',//根据商品类型获取商品
		getGoodsListByCuntryId : server_host + 'goods/getGoodsListByCuntryId',//根据国家查询商品
		getGoodsList : server_host + 'goods/getGoodsList',//获取商品列表
		getGoodsInfo : server_host + 'goods/getGoodsInfo',//获取商品详情
		addVisaHouseholdsImgInfo : server_host + 'visaHouseholdsImg/addVisaHouseholdsImgInfo',//添加户口信息
		delVisaHouseholdsImgInfo : server_host + 'visaHouseholdsImg/delVisaHouseholdsImgInfo',//删除户口信息
		getVisaHouseholdsImgInfo : server_host + 'visaHouseholdsImg/getVisaHouseholdsImgInfo',//获取户口信息
		addVisaApplyPersonImgInfo : server_host + 'visaApplyPersonImg/addVisaApplyPersonImgInfo',//添加申请人照片
		delVisaApplyPersonImgInfo : server_host + 'visaApplyPersonImg/delVisaApplyPersonImgInfo',//删除申请人照片
		getVisaApplyPersonImgInfo : server_host + 'visaApplyPersonImg/getVisaApplyPersonImgInfo',//获取申请人照片
		saveVisaMarriageImgInfo : server_host + 'visaMarriageImg/saveVisaMarriageImgInfo',//添加婚姻状况
		delVisaMarriageImgInfo : server_host + 'visaMarriageImg/delVisaMarriageImgInfo',//删除婚姻状况
		getVisaMarriageImgInfo : server_host + 'visaMarriageImg/getVisaMarriageImgInfo',//获取婚姻状况
		addVisaPropertyImgInfo : server_host + 'visaPropertyImg/addVisaPropertyImgInfo',//添加辅助资产
		delVisaPropertyImgInfo : server_host + 'visaPropertyImg/delVisaPropertyImgInfo',//删除辅助资产
		getVisaPropertyImgInfo : server_host + 'visaPropertyImg/getVisaPropertyImgInfo',//获取辅助资产		
		addPassport : server_host + 'passport/addPassport',//添加护照信息
		delPassportInfo : server_host + 'passport/delPassportInfo',//删除护照信息
		getPassportInfoImg : server_host + 'passport/getPassportInfoImg',//获取护照信息
		addVisaEmergencyPerson : server_host + 'emergencyPerson/addVisaEmergencyPerson',//添加紧急联系人
		getVisaEmergencyPersonInfo : server_host + 'emergencyPerson/getVisaEmergencyPersonInfo',//获取紧急联系人
		addVisaOrderInfo : server_host + 'order/addVisaOrderInfo',//添加订单
		getVisaApplyCustomerInfoById : server_host + 'applyCustomer/getVisaApplyCustomerInfoById',
		getOrderApplyTableForCustomerInfo : server_host + 'OrderApplyTableForCustomer/getOrderApplyTableForCustomerInfo',//获取订单申请人信息
		getOrderApplyTableDataInfo : server_host + 'OrderApplyTableForCustomer/getOrderApplyTableDataInfo',//获取订单申请人详细完成情况
		addTravelInfo : server_host + 'travelInfo/addTravelInfo',//添加旅行信息
		getTravelInfo : server_host + 'travelInfo/getTravelInfo',//获取旅行信息
		addStudentCertificate : server_host + 'studentCertificate/addStudentCertificate',//添加学生证信息
		getStudentCertificate : server_host + 'studentCertificate/getStudentCertificate',//获取学生证信息
		addBirthCertificate : server_host + 'birthCertificate/addBirthCertificate',//添加出生证信息
		getBirthCertificate : server_host + 'birthCertificate/getBirthCertificate',//获取出生证信息
		addRetiredCertificate : server_host + 'retiredCertificate/addRetiredCertificate',//添加退休证信息
		getRetiredCertificate : server_host + 'retiredCertificate/getRetiredCertificate',//获取退休证信息
		addMarriageCertificate : server_host + 'marriageCertificate/addMarriageCertificate',//添加父母结婚证信息
		getMarriageCertificate : server_host + 'marriageCertificate/getMarriageCertificate',//获取父母结婚证信息
		confirmOrder : server_host + 'order/confirmOrder',//获取确认订单的基本信息
		getOrderAppPhotoDataInfo : server_host + 'order/getOrderAppPhotoDataInfo',//订单拍摄资料
		getOrderList : server_host + 'order/getOrderList',//订单列表
		deleteOrder : server_host + 'order/deleteOrder',//删除订单
		wxConfig : server_host + 'wx/wxConfig',//微信初始化数据
		perpayH5 : server_host + 'pay/perpayH5',//h5支付
		perpay : server_host + 'pay/perpay',//微信支付生成预支付
		findAllVisaDataType : server_host + 'visaDataType/findAllVisaDataType',//获取职位信息
		getPostDataOrAppPhotoData : server_host + 'goods/getPostDataOrAppPhotoData',//获取邮寄资料或者拍摄资料描述
		getOrderInfo : server_host + 'order/getOrderInfo',//获取订单详细
		getHomePageList: server_host + 'tickets/getHomePageList',//获取首页列表
		getTicketsList: server_host + 'tickets/getTicketsList',//获取门票列表
		getTicketsInfo: server_host + 'tickets/getTicketsInfo',//获取门票详情
		addCollection: server_host + 'collection/addCollection',//添加收藏
		getTravelVouchersList: server_host + 'travelVouchers/getTravelVouchersList',//获取周游券列表
		getTravelVouchersInfo: server_host + 'travelVouchers/getTravelVouchersInfo',//获取周游券详情
		getVisaEvaluationList: server_host + 'evaluation/getVisaEvaluationList',//获取评论列表
		getCollectionList: server_host + 'collection/getCollectionList',//获取收藏列表
		delCollectionList: server_host + 'collection/delCollectionList',//删除我的收藏
		getBrowseList: server_host + 'browse/getBrowseList',//获取个人浏览记录
		addVisaTravelOrder: server_host + 'visaTravelOrder/addVisaTravelOrder',//门票、周游券下单
		travelOrderPerpayH5 : server_host + 'visaTravelOrder/travelOrderPerpayH5',//门票、周游券h5支付
		travelOrderPerpay: server_host + 'visaTravelOrder/travelOrderPerpay',//门票、周游券微信支付
		getTravelOrderList: server_host + 'visaTravelOrder/getTravelOrderList',//门票、周游券订单列表
		updateTravelOrderList: server_host + 'visaTravelOrder/updateTravelOrderList',//确认出行
		addVisaEvaluation: server_host + 'evaluation/addVisaEvaluation',//去评价
		getCityList: server_host + 'city/getCityList',//获取城市列表
		getCarTypeList: server_host +'carType/getCarTypeList',//租车类型
		getCarList: server_host + 'car/getCarList',//租车列表
		getCarInfo: server_host + 'car/getCarInfo',//租车详情
	},
	/**
	 * ajax请求
	 * @param {Object} url请求连接
	 * @param {Object} data请求参数
	 * @param {Object} callback回调函数
	 */
	postData : function(url, data, callback) {
//		base.setWait("正在获取数据...");
		console.log(url+"?"+JSON.stringify(data));
		$.ajax({  
            type: "post", //HTTP请求类型 
            url: url,  
            data: data,  
            dataType: 'json', //服务器返回json格式数据
            timeout:20000,//超时时间设置为20秒；
            success: function (data) {
            		base.clearWait();
            		console.log(data);
            		callback(data);
            }, //服务器返回响应
            error: function (xhr,type,errorThrown) {  
            		base.clearWait();
                //异常处理；
				console.log(type);
				if(this.spinner != null && this.spinner != ''){
					base.clearWait();
				}
//				mui.toast("请求出错！");  
            }  
        });
	},
	/**
	 * ajax请求
	 * @param {Object} url请求连接
	 * @param {Object} data请求参数
	 * @param {Object} callback回调函数
	 */
	postFileData : function(url, data, callback) {
//		base.setWait("正在获取数据...");
		console.log(url+"?"+JSON.stringify(data));
		$.ajax({
            url: url,
            method: 'post',
            data: data,
            contentType: false, // 注意这里应设为false
            processData: false,
            cache: false,
            success: function(data) {
            		console.log(data);
            		base.clearWait();
            		mui.toast(data.message);
            		callback(data);
            },
            error: function (jqXHR) {
            		base.clearWait();
            		mui.toast("上传失败，请稍后再试！");
                console.log(JSON.stringify(jqXHR));
            }
        })
	},
	/**
	 * 获取URL链接参数，在通过URL跳转页面时，可通过此方法获取URL的参数
	 * @param {Object} val要获取的参数名称
	 */
	getParameter : function(val){
		var uri = window.location.search;
		var re = new RegExp("" + val + "=([^&?]*)", "ig");
		var str = ((uri.match(re)) ? (uri.match(re)[0].substr(val.length + 1)) : "");
		return decodeURIComponent(str);
	},
	getSavedData: function() {
		var history = JSON.parse(storege[HISTORY] || '[]');
		var item = history[history.length - 1];
		if (!item) {
			console.log('save:', {});
			return {};
		}
		var path = window.location.pathname;
		if (item.path == path) {
			history.pop();
			storege[HISTORY] = JSON.stringify(history);
			scrollTop = item.scrollTop;
			this.from = item.from;
			this.isBack = true;
			console.log('save:', item.saved || {});
			return item.saved || {};
		} else {
			this.from = item.path;
			this.isBack = false;
			console.log('save:', item.saved || {});
			return {};
		}
	},
	showView: function(url, param, saved, getScrollTop) {
		scrollTop = undefined;
		var history = JSON.parse(storege[HISTORY] || '[]');
		history.push({
			href: window.location.href,
			path: window.location.pathname,
			saved: saved,
			scrollTop: getScrollTop ? getScrollTop() : $(document.body).scrollTop(),
			from: getAbsolutePath(url, window.location.pathname),
		});
		storege[HISTORY] = JSON.stringify(history);
		storege[TRANS_PARAM] = JSON.stringify(param||{});
		window.location.href = url;
	},
	/**
	 * 设置等待加载
	 * @param {Object} text
	 */
	setWait: function(text) {
        var opts = {
            lines: 12, // 花瓣数目
            length: 10, // 花瓣长度
            width: 3, // 花瓣宽度
            radius: 10, // 花瓣距中心半径
            corners: 1, // 花瓣圆滑度 (0-1)
            rotate: 0, // 花瓣旋转角度
            direction: 1, // 花瓣旋转方向 1: 顺时针, -1: 逆时针
            color: '#FBDC9F', // 花瓣颜色
            speed: 1, // 花瓣旋转速度
            trail: 60, // 花瓣旋转时的拖影(百分比)
            shadow: false, // 花瓣是否显示阴影
            hwaccel: false, //spinner 是否启用硬件加速及高速旋转
            className: 'spinner', // spinner css 样式名称
            zIndex: 2e9, // spinner的z轴 (默认是2000000000)
    //      top: 'auto', // spinner 相对父容器Top定位 单位 px
    //      left: 'auto'// spinner 相对父容器Left定位 单位 px
        };
    	this.spinner = new Spinner(opts);
        $(document.body).append('<div id="mask_container"><div class="modal-backdrop"></div><div class="spinner-text-container">'+text+'</div></div>');
    	this.spinner.spin(document.body);//打开等待加载
    },
    clearWait: function() {
        $("#mask_container").remove();
        if (this.spinner != null) {
        	this.spinner.spin();//关闭等待加载	
        }
        this.spinner = null;
    },
    /**
	 * 是否是微信浏览器
	 */
	isOnWx: function() {
		var ua = window.navigator.userAgent.toLowerCase();
        if(ua.match(/MicroMessenger/i) == 'micromessenger'){
            return true;
        } else {
            return false;
        }
	},
    /**
	 * 初始化配置
	 * @param onReady 初始化成功后的回调
	 */
	initWX: function(onReady) {
		//避免重复调用
		if(cache.wxInited) {
			return;
		}
		cache.wxInited = true;

		if(!base.isOnWx()) {
			console.info("please debug this page on weixin browser.");
			return;
		}
		
//		var url = encodeURIComponent(location.href);
		var url = window.location.href;
		base.postData(base.url.wxConfig,{url: url},function(res){
			var data = res.extendData;
			wx.config({
				debug: false,
				appId : data.appId,
				timestamp: data.timestamp, //生成签名的时间戳
				nonceStr: data.nonceStr, //生成签名的随机串
				signature: data.signature,//签名
				jsApiList: ['getLocation', 'openLocation', 'chooseWXPay', 'chooseImage', 'previewImage', 'uploadImage','onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone','closeWindow'] //需要使用的JS接口列表
			});
		});

		wx.ready(function(){
			//mui.toast("微信初始化成功！");
			if(onReady != null) {
				onReady();
			}
		});

		wx.error(function(res){
			mui.toast("微信初始化失败！");
		});
	},
	/**
	 * 统一绑定分享按钮事件
	 */
	bindShare: function(shareData) {
		shareData.success = shareData.success|| function () { // 用户确认分享后执行的回调函数
			//do noting
			mui.toast('success');
		},
		shareData.cancel = shareData.cancel||function () { // 用户取消分享后执行的回调函数
			//do noting
			mui.toast('cancel');
		}
		wx.onMenuShareTimeline(shareData);//朋友圈
		wx.onMenuShareAppMessage(shareData);//微信好友
		wx.onMenuShareQQ(shareData);//qq
		wx.onMenuShareWeibo(shareData);//微博
		wx.onMenuShareQZone(shareData);//qq空间
		 
		//隐藏一些没什么用的按钮		
 

	},
	/**
	 * 微信支付
	 */
	weChatPay: function(params, onSuccess, onCancel, onFail) {
		if(!base.isOnWx()) {
			mui.toast("请在微信端调用此功能");
			return;
		}
		base.setWait('正在加载...');
		base.postData(base.url.perpay, params, function(data){//下微信预付单
			if (data.success) {
				var cfg = data.extendData;
				//weui.dialog(JSON.stringify(cfg));
				wx.chooseWXPay({
					timestamp: cfg.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
					nonceStr: cfg.nonceStr, // 支付签名随机串，不长于 32 位
					package: cfg.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
					signType: cfg.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
					paySign: cfg.paySign, // 支付签名
					success: function (res) {
						base.clearWait();
						if(onSuccess) {
							onSuccess(res);
						}
					},
					cancel: function(res) {
						base.clearWait();
						//mui.toast("支付被取消");
						if(onCancel) {
							onCancel();
						}
					},
					fail: function(res, arg2) {
						base.clearWait();
						mui.toast("对不起，支付失败:"+JSON.stringify(res)+","+JSON.stringify(arg2));
						if(onFail) {
							onFail();
						}
					}
				});
			}else{
				base.clearWait();
				mui.toast(data.msg);
			}
		});
	},
	/**
	 * 微信支付（门票、周游券）
	 * @param {Object} params
	 * @param {Object} onSuccess
	 * @param {Object} onCancel
	 * @param {Object} onFail
	 */
	weChatPayTravel: function(params, onSuccess, onCancel, onFail) {
		if(!base.isOnWx()) {
			mui.toast("请在微信端调用此功能");
			return;
		}
		base.setWait('正在加载...');
		base.postData(base.url.travelOrderPerpay, params, function(data){//下微信预付单
			if (data.success) {
				var cfg = data.extendData;
				//weui.dialog(JSON.stringify(cfg));
				wx.chooseWXPay({
					timestamp: cfg.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
					nonceStr: cfg.nonceStr, // 支付签名随机串，不长于 32 位
					package: cfg.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
					signType: cfg.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
					paySign: cfg.paySign, // 支付签名
					success: function (res) {
						base.clearWait();
						if(onSuccess) {
							onSuccess(res);
						}
					},
					cancel: function(res) {
						base.clearWait();
						//mui.toast("支付被取消");
						if(onCancel) {
							onCancel();
						}
					},
					fail: function(res, arg2) {
						base.clearWait();
						mui.toast("对不起，支付失败:"+JSON.stringify(res)+","+JSON.stringify(arg2));
						if(onFail) {
							onFail();
						}
					}
				});
			}else{
				base.clearWait();
				mui.toast(data.msg);
			}
		});
	},
	getNowFormatToday : function(){
		var date = new Date();
	    var month = date.getMonth() + 1;
	    var strDate = date.getDate();
	    if (month >= 1 && month <= 9) {
	        month = "0" + month;
	    }
	    if (strDate >= 0 && strDate <= 9) {
	        strDate = "0" + strDate;
	    }
	    var currentdate = date.getFullYear() + "-" + month + "-" + strDate;
	    return currentdate;
	}
    
}

app.global = (function() {
	var ls = window.localStorage;
	var GLOBAL = "app_global";
	var global = {
		set: function(key, data) {
			var global = JSON.parse(ls[GLOBAL] || '{}');
			global[key] = data;
			ls[GLOBAL] = JSON.stringify(global);
		},
		add: function(key, data) {
			var global = JSON.parse(ls[GLOBAL] || '{}');
			global[key].push(data);
			ls[GLOBAL] = JSON.stringify(global);
		},
		get: function(key) {
			var global = JSON.parse(ls[GLOBAL] || '{}');
			return global[key];
		},
		getOnce: function(key) {
			var global = JSON.parse(ls[GLOBAL] || '{}');
			var ret = global[key];
			if (ret != null) {
				delete global[key];
			}
			ls[GLOBAL] = JSON.stringify(global);
			return ret;
		},
		clear: function(key) {
			var global = JSON.parse(ls[GLOBAL] || '{}');
			delete global[key];
			ls[GLOBAL] = JSON.stringify(global);
		}
	};
//	console.log('global:', ls[GLOBAL]);
	return global;
})();

function getAbsolutePath(from, path) {
	if (from[0] === '/') {
		return from;
	}
	var parr = path.split('/').slice(0, -1);
	var farr = from.split('/');
	for (var i in farr) {
		var item = farr[i];
		if (item === '.') {
			continue;
		} else if (item === '..') {
			parr.pop();
		} else {
			parr.push(item);
		}
	}
	return parr.join('/');
}
